package com.htudata.zabbix.history.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.List;

import com.htudata.core.util.operation.ArrayOperationUtils;
import com.htudata.core.util.operation.CollectionsOperationUtils;
import com.htudata.zabbix.api.service.HistoryZabbixApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class HistoryService {

  @Autowired
  private HistoryZabbixApiService historyZabbixApiService;
  
  public <T> JSONArray getHistory(String[] hostIdArr, List<T> itemIdList, int history, int time_from, int time_till, int limit) throws Exception {
    JSONObject params = new JSONObject();
    if (limit > 0)
      params.put("limit", Integer.valueOf(limit)); 
    params.put("sortfield", "clock");
    params.put("sortorder", "DESC");
    if (ArrayOperationUtils.isValidArr((Object[])hostIdArr))
      params.put("hostids", hostIdArr); 
    if (CollectionsOperationUtils.isValidCollection(itemIdList))
      params.put("itemids", itemIdList); 
    params.put("history", Integer.valueOf(history));
    if (time_from > 0)
      params.put("time_from", Integer.valueOf(time_from)); 
    if (time_till > 0)
      params.put("time_till", Integer.valueOf(time_till)); 
    String json = this.historyZabbixApiService.getHistory(params);
    JSONObject root = JSON.parseObject(json);
    if (root == null)
      return null; 
    JSONArray result = root.getJSONArray("result");
    return result;
  }
}
